<?php
require_once "www/_include/smarty/libs/Smarty.class.php";
require_once "services/FacebookProxy.php";
require_once "data/dao/CountryDAO.php";
require_once "utils/HTTPRequest.php";
require_once "data/dao/UserDAO.php";
require_once "application/game/Locale.php";

class UserProfileRenderer{
	
	private $user;
	private $smarty;

	public function UserProfileRenderer(){
			
		$this->smarty = new Smarty();
		
		$facebook = new FacebookProxy();
		$facebook->requireFrame();
		$userId = $facebook->requireLogin(); 	
		
		$udao = new UserDAO();
		$this->user = $udao->findUser($userId);
		
		$do = HTTPRequest::getParam("do");
		if ($do == "update"){
			$details = array(
				"first-name" => HTTPRequest::getParam("first-name"),
				"last-name" => HTTPRequest::getParam("last-name"),
				"location" => HTTPRequest::getParam("country"),
				"wii-code" => HTTPRequest::getParam("wii-code"),
				"amazon-store" => HTTPRequest::getParam("amazon-store")
			);
			$this->updateUserDetails($details);
			// get the user again, because details have been updated
			$this->user = $udao->findUser($userId);
		}

		
		$this->getPlaceholderValues($do);
		$this->renderPage();
	}
	
	private function getPlaceholderValues($mode){

		$this->smarty->assign("styleSheet", file_get_contents("./html/wiiSocial.css"));
		$this->smarty->assign("javaScript", file_get_contents("./html/wiiSocial.js"));
		$this->smarty->assign("firstname", $this->user->getFirstName());
		$this->smarty->assign("lastname", $this->user->getLastName());
		$this->smarty->assign("imageSrc", $this->user->getProfilePicBigUrl());
		$this->smarty->assign("HOST", HOST_URL);
		
		$cdao = new CountryDAO();		
		$this->smarty->assign("countries", $cdao->getCountryMap());
		$this->smarty->assign("amazonLocales", Locale::getAllAmazonLocales());
		
		$this->smarty->assign("locationString", $this->user->getLocationString());
		$this->smarty->assign("locationCode", $this->user->getLocationISO3166A2());
		$this->smarty->assign("wiiCode", $this->user->getWiiCode());
		
		$s = Locale::getAllAmazonLocales();
		$this->smarty->assign("storeCode", $this->user->getStoreLocation());
		$this->smarty->assign("storeString", $s[$this->user->getStoreLocation()]);
		
		if ($mode == "edit"){
			$this->smarty->assign("edit", true);
		}
	}
	
	private function renderPage(){
		$this->smarty->display("user-profile.tpl");
	}
	
	private function updateUserDetails(array $details){
	
		$udao = new UserDAO();
		return $udao->updateUserDetails($this->user->getUserId(), $details);
	}
}
$upr = new UserProfileRenderer();
?>